package club.babyf.springai.jimmer;

import cn.dev33.satoken.stp.StpUtil;
import lombok.AllArgsConstructor;
import org.babyfish.jimmer.sql.DraftInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class BaseEntityDraftInterceptor implements DraftInterceptor<BaseEntity, BaseEntityDraft> {

    @Override
    public void beforeSave(@NotNull BaseEntityDraft draft, BaseEntity baseEntity) {
        String loginIdAsString;
        try {
            loginIdAsString = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            loginIdAsString = "";
        }
        String finalLoginIdAsString = loginIdAsString;
        draft.applyEditor(user -> user.setId(finalLoginIdAsString));
        if (baseEntity == null) {
            draft.applyCreator(user -> user.setId(finalLoginIdAsString));
        }
    }

}
